package controller

import (
	"lion-passport/internal/service"
	"lion-passport/internal/types"
	"lion-passport/internal/utils"
	"lion-passport/internal/utils/log"
	"net/http"

	"github.com/gin-gonic/gin"
)

func LoginHandler(c *gin.Context) {
	var req types.VcodeLoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		log.LogrusObj.Infoln(err)
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request format"})
		return
	}

	// Call the logic layer to handle the login
	token, err := service.VcodeLogin(req, c)
	if err != nil {
		log.LogrusObj.Infoln(err)
		c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, utils.RespSuccess(c, token))
}

func TokenRefreshHandler(c *gin.Context) {
	// Get the refresh token from the request header
	var req types.RefreshTokenRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		log.LogrusObj.Infoln(err)
		c.JSON(http.StatusBadRequest, gin.H{"error": "Missing refresh token"})
		return
	}

	refreshToken := req.RefreshToken
	if refreshToken == "" {
		log.LogrusObj.Infoln("Refresh token is required")
		c.JSON(http.StatusBadRequest, gin.H{"error": "Refresh token is required"})
		return
	}

	// Call the logic layer to handle the token refresh
	newToken, err := service.RefreshToken(refreshToken, c)
	if err != nil {
		log.LogrusObj.Infoln(err)
		c.JSON(http.StatusOK, utils.RespError(305208, err.Error()))
		return
	}

	c.JSON(http.StatusOK, utils.RespSuccess(c, newToken))
}